package com.haoxuer.discover.useroauth.plugs.oschina;

import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.haoxuer.discover.user.oauth.domain.OauthResponse;
import com.haoxuer.discover.user.oauth.domain.TokenResponse;
import com.haoxuer.discover.user.oauth.impl.OsChinaHander;
import com.haoxuer.discover.useroauth.plugs.base.OauthPlugin;
import com.haoxuer.discover.useroauth.plugs.domain.OauthInfo;
import com.haoxuer.discover.useroauth.scribejava.apis.OschinaApi;
import com.haoxuer.discover.plug.data.entity.PluginConfig;
import org.springframework.stereotype.Component;

@Component("oschina_plugin")
public class OsChinaPlugin extends OauthPlugin {
  
  @Override
  public OauthInfo info() {
    OauthInfo result = new OauthInfo();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String apikey = pluginConfig.getAttribute("apikey");
      String secret = pluginConfig.getAttribute("secret");
      String callback = pluginConfig.getAttribute("callback");
      String scope = pluginConfig.getAttribute("scope");
      String icon = pluginConfig.getAttribute("icon");
      String name = pluginConfig.getAttribute("name");
      String bg = pluginConfig.getAttribute("bg");
  
      OAuth20Service github = new ServiceBuilder(apikey)
          .apiSecret(secret)
          .callback(callback).scope(scope).responseType("code")
          .build(OschinaApi.instance());
      result.setUrl(github.getAuthorizationUrl());
      result.setIcon(icon);
      result.setName(name);
      result.setBg(bg);
    }
    return result;
  }
  
  @Override
  public OauthResponse handle(String code) {
    OauthResponse result = null;
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String apikey = pluginConfig.getAttribute("apikey");
      String secret = pluginConfig.getAttribute("secret");
      String redirect_uri = pluginConfig.getAttribute("redirect_uri");
  
      OsChinaHander hander = new OsChinaHander();
      hander.setKey(apikey);
      hander.setSecret(secret);
      hander.setRedirect_uri(redirect_uri);
      TokenResponse tokenResponse = hander.getToken(code);
      result = hander.login(tokenResponse.getAccessToken(), null);
    }
    return result;
  }
  
  @Override
  public String getName() {
    return "开源中国第三方登陆插件";
  }
  
  @Override
  public String getVersion() {
    return "1.01";
  }
  

  @Override
  public String viewName() {
    return "oschina";
  }
}
